<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/10/04 23:22:59 $)
// $RCSfile: mobile_push.php,v $ : $Revision: 1.6 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

$template->loadLanguageSection("mobile");
$template->loadLanguageSection("staff_tickets");
$template->loadLanguageSection("tickets_auditlogs");
require_once ("./modules/tickets/functions_ticketsui.php");
require_once ("./modules/tickets/functions_ticketmain.php");
require_once ("./modules/tickets/functions_search.php");
require_once ("./modules/tickets/functions_ticketcore.php");
require_once ("./modules/tickets/functions_mobile.php");
require_once ("./includes/functions_xml.php");

/*
RESULT OUTPUT

<mobile>
	<success>1</success>
	<errors>2</errors>

	<error>
		<ticketid>0</ticketid>
		<message>Invalid XML Data Received</message>
	<error>
	<error>
		<ticketid>67890</ticketid>
		<message>Failed to update priority, Not enough permissions</message>
	<error>
</mobile>

SAMPLE INCOMING DATA:
<mobile>
<reply>
    <ticketid>123456</ticketid>
    <contents>Hello, this is a reply.</contents>
	<attachment>
		<filename>test.jpg</filename>
		<contents>boo</contents>
	</attachment>
	<attachment>
		<filename>test2.jpg</filename>
		<contents>boo2</contents>
	</attachment>
</reply>
<reply>
    <ticketid>123456</ticketid>
    <contents>Hello, this is a reply.</contents>
</reply>
<note>
    <ticketid>123456</ticketid>
    <type>[user, ticket]</type>
    <contents>Dude: Look into this issue</contents>
</note>
<note>
    <ticketid>123456</ticketid>
    <type>[user, ticket]</type>
    <contents>Dude: Look into this issue</contents>
</note>
<billing>
    <ticketid>123456</ticketid>
    <workerstaffid>1</workerstaffid>
    <timespent>[time spent in seconds]</timespent>
    <timebillable>[time billable in seconds]</timebillable>
    <notes>I did blah, blah, and blah.</notes>
</billing>
<propchange>
    <ticketid>123456</ticketid>
    <type>[owner, department, status, priority]</type>
    <data>[owner=new staff id, department=new dept. id, status=new status id, priority=new priority id]</data>
</propchange>
</mobile>
*/

// We first parse the incoming XML
$xml = new XML;

$_assigns = getAssignedDepartments(MODULE_TICKETS);
$_tree = $xml->xml2tree($_POST["xml"]);

/*ob_start();
echo $_POST["xml"]."\n";
print_r($_tree);
$contents = ob_get_contents();
ob_end_clean();
$fp = fopen("./cache/km.txt", "w+");
fwrite($fp, $contents);
fclose($fp);*/

if (_is_array($_tree))
{
	$_tree = $_tree["mobile"][0]["children"];
	$_errors = $_success = array();
	$_successcount = 0;
	$_ticketObjStore = array();

	/**
	* ###############################################
	* INCOMING REPLIES
	* ###############################################
	*/
	if (_is_array($_tree["reply"]))
	{
		foreach ($_tree["reply"] as $key=>$val)
		{
			$_ticketid = $val["children"]["ticketid"][0]["values"][0];
			$_contents = $val["children"]["contents"][0]["values"][0];

			$_ticketObjStore[$_ticketid] = new TicketMain($_ticketid);
			$_ticketObj = &$_ticketObjStore[$_ticketid];

			if (empty($_ticketObj->ticket["ticketid"]))
			{
				$_errors[] = array("ticketid" => $_ticketObj->ticket["fticketid"], "type" => "reply", "message" => sprintf($_SWIFT["language"]["invalidmobileticket"], $_ticketid));
				continue;
			} else if (!in_array($_ticketObj->ticket["departmentid"], $_assigns)) {
				$_errors[] = array("ticketid" => $_ticketObj->ticket["fticketid"], "type" => "reply", "message" => sprintf($_SWIFT["language"]["notassignedmobileticket"], $_ticketObj->ticket["fticketid"]));
				continue;
			}

			$_attachments = array();
			if (_is_array($val["children"]["attachment"]))
			{
				$_attachindex = 0;
				foreach ($val["children"]["attachment"] as $attachkey=>$attachval)
				{
					$_splitdata = explode(";", $attachval["children"]["contents"][0]["values"][0]);
					$_attachcontents = '';
					foreach ($_splitdata as $splitkey=>$splitval)
					{
						if (trim($splitval) != "")
						{
							$_attachcontents .= base64_decode($splitval);
						}
					}
					$_attachments[$_attachindex]["contents"] = $_attachcontents;
					$_attachments[$_attachindex]["filesize"] = strlen($_attachcontents);
					$_attachments[$_attachindex]["filename"] = $attachval["children"]["filename"][0]["values"][0];
					$_attachments[$_attachindex]["contenttype"] = "application/octet-stream";

					$_attachindex++;
				}
			}

			$_ticketObj->createStaffReply($_SWIFT["staff"]["staffid"], $_SWIFT["staff"]["fullname"], $_SWIFT["staff"]["email"], $_ticketObj->ticket["subject"], $_contents, false, $_ticketObj->ticket["emailqueueid"], $_attachments, "", false, "", false, false, true);
			$_ticketObj->processTicketQueries();
			$_success[] = array("ticketid" => $_ticketObj->ticket["ticketid"], "ticketdisplayid" => $_ticketObj->ticket["fticketid"], "type" => "reply", "data" => "0");
			$_successcount++;
		}
	}



	/**
	* ###############################################
	* INCOMING NOTES
	* ###############################################
	*/
	if (_is_array($_tree["note"])) {
		foreach ($_tree["note"] as $key=>$val)
		{
			$_ticketid = $val["children"]["ticketid"][0]["values"][0];
			$_notetype = $val["children"]["type"][0]["values"][0];
			$_contents = $val["children"]["contents"][0]["values"][0];

			if (is_object($_ticketObjStore[$_ticketid]))
			{
				$_ticketObj = &$_ticketObjStore[$_ticketid];
			} else {
				$_ticketObjStore[$_ticketid] = new TicketMain($_ticketid);
				$_ticketObj = &$_ticketObjStore[$_ticketid];
			}

			if (empty($_ticketObj->ticket["ticketid"]))
			{
				$_errors[] = array("ticketid" => $_ticketObj->ticket["fticketid"], "type" => "note", "message" => sprintf($_SWIFT["language"]["invalidmobileticket"], $_ticketid));
				continue;
			} else if (!in_array($_ticketObj->ticket["departmentid"], $_assigns)) {
				$_errors[] = array("ticketid" => $_ticketObj->ticket["fticketid"], "type" => "note", "message" => sprintf($_SWIFT["language"]["notassignedmobileticket"], $_ticketObj->ticket["fticketid"]));
				continue;
			}

			if ($_notetype == "user")
			{
				$_ticketnotetype = NOTE_USER;
			} else {
				$_ticketnotetype = NOTE_TICKET;
			}

			$_ticketObj->addTicketNote($_ticketnotetype, "0", $_contents);
			$_ticketObj->processTicketQueries();
			$_success[] = array("ticketid" => $_ticketObj->ticket["ticketid"], "ticketdisplayid" => $_ticketObj->ticket["fticketid"], "type" => "note", "data" => "0");
			$_successcount++;
		}
	}



	/**
	* ###############################################
	* INCOMING BILLING ENTRIES
	* ###############################################
	*/
	if (_is_array($_tree["billing"]))
	{
		foreach ($_tree["billing"] as $key=>$val)
		{
			$_ticketid = $val["children"]["ticketid"][0]["values"][0];
			$_workerstaffid = $val["children"]["workerid"][0]["values"][0];
			$_timespent = $val["children"]["timespent"][0]["values"][0];
			$_timebillable = $val["children"]["timebillable"][0]["values"][0];
			$_kmbillingid = $val["children"]["billingid"][0]["values"][0];
			$_notes = $val["children"]["notes"][0]["values"][0];

			if (is_object($_ticketObjStore[$_ticketid]))
			{
				$_ticketObj = &$_ticketObjStore[$_ticketid];
			} else {
				$_ticketObjStore[$_ticketid] = new TicketMain($_ticketid);
				$_ticketObj = &$_ticketObjStore[$_ticketid];
			}

			if (empty($_ticketObj->ticket["ticketid"]))
			{
				$_errors[] = array("ticketid" => $_ticketObj->ticket["fticketid"], "type" => "billing", "message" => sprintf($_SWIFT["language"]["invalidmobileticket"], $_ticketid));
				continue;
			} else if (!in_array($_ticketObj->ticket["departmentid"], $_assigns)) {
				$_errors[] = array("ticketid" => $_ticketObj->ticket["fticketid"], "type" => "billing", "message" => sprintf($_SWIFT["language"]["notassignedmobileticket"], $_ticketObj->ticket["fticketid"]));
				continue;
			}

			$timetrackid = $_ticketObj->addBillingEntry(DATENOW, intval($_timespent), intval($_timebillable), intval($_workerstaffid), $_notes);
			$_ticketObj->processTicketQueries();
			$_success[] = array("ticketid" => $_ticketObj->ticket["ticketid"], "ticketdisplayid" => $_ticketObj->ticket["fticketid"], "type" => "billing", "data" => $_kmbillingid);

			$_successcount++;
		}

	}



	/**
	* ###############################################
	* INCOMING PROPERTY CHANGES
	* ###############################################
	*/
	if (_is_array($_tree["propchange"]))
	{
		foreach ($_tree["propchange"] as $key=>$val)
		{
			$_ticketid = $val["children"]["ticketid"][0]["values"][0];
			$_type = $val["children"]["type"][0]["values"][0];
			$_data = $val["children"]["data"][0]["values"][0];

			if (is_object($_ticketObjStore[$_ticketid]))
			{
				$_ticketObj = &$_ticketObjStore[$_ticketid];
			} else {
				$_ticketObjStore[$_ticketid] = new TicketMain($_ticketid);
				$_ticketObj = &$_ticketObjStore[$_ticketid];
			}

			if (empty($_ticketObj->ticket["ticketid"]))
			{
				$_errors[] = array("ticketid" => $_ticketObj->ticket["fticketid"], "type" => "propchange", "message" => sprintf($_SWIFT["language"]["invalidmobileticket"], $_ticketid));
				continue;
			} else if (!in_array($_ticketObj->ticket["departmentid"], $_assigns)) {
				$_errors[] = array("ticketid" => $_ticketObj->ticket["fticketid"], "type" => "propchange", "message" => sprintf($_SWIFT["language"]["notassignedmobileticket"], $_ticketObj->ticket["fticketid"]));
				continue;
			}

			// ======= CHANGE OWNER =======
			if ($_type == "owner" && !empty($_SWIFT["staffcache"][$_data]["staffid"]))
			{
				$_ticketObj->assignTicket(intval($_data));
				$_success[] = array("ticketid" => $_ticketObj->ticket["ticketid"], "ticketdisplayid" => $_ticketObj->ticket["fticketid"], "type" => "propchange", "data" => "owner");
				$_successcount++;

			// ======= CHANGE OWNER - INVALID STAFF =======
			} else if ($_type == "owner" && empty($_SWIFT["staffcache"][$_data]["staffid"])) {
				$_errors[] = array("ticketid" => $_ticketObj->ticket["fticketid"], "type" => "propchange", "message" => sprintf($_SWIFT["language"]["invalidmobilestaff"], $_data));
				continue;

			
			// ======= CHANGE DEPARTMENT =======
			} else if ($_type == "department" && !empty($_SWIFT["departmentcache"][$_data]["departmentid"])) {
				$_ticketObj->moveTicket(intval($_data));
				$_success[] = array("ticketid" => $_ticketObj->ticket["ticketid"], "ticketdisplayid" => $_ticketObj->ticket["fticketid"], "type" => "propchange", "data" => "department");
				$_successcount++;

			// ======= CHANGE DEPARTMENT - INVALID DEPARTMENT =======
			} else if ($_type == "department" && empty($_SWIFT["departmentcache"][$_data]["departmentid"])) {
				$_errors[] = array("ticketid" => $_ticketObj->ticket["fticketid"], "type" => "propchange", "message" => sprintf($_SWIFT["language"]["invalidmobiledep"], $_data));
				continue;

			// ======= CHANGE STATUS =======
			} else if ($_type == "status" && !empty($_SWIFT["statuscache"][$_data]["ticketstatusid"])) {
				$_ticketObj->changeStatus(intval($_data));
				$_success[] = array("ticketid" => $_ticketObj->ticket["ticketid"], "ticketdisplayid" => $_ticketObj->ticket["fticketid"], "type" => "propchange", "data" => "status");
				$_successcount++;

			// ======= CHANGE STATUS - INVALID STATUS =======
			} else if ($_type == "status" && !empty($_SWIFT["statuscache"][$_data]["ticketstatusid"])) {
				$_errors[] = array("ticketid" => $_ticketObj->ticket["fticketid"], "type" => "propchange", "message" => sprintf($_SWIFT["language"]["invalidmobilestatus"], $_data));
				continue;

			// ======= CHANGE PRIORITY =======
			} else if ($_type == "priority" && !empty($_SWIFT["prioritycache"][$_data]["priorityid"])) {
				$_ticketObj->changePriority(intval($_data));
				$_success[] = array("ticketid" => $_ticketObj->ticket["ticketid"], "ticketdisplayid" => $_ticketObj->ticket["fticketid"], "type" => "propchange", "data" => "priority");
				$_successcount++;

			} else if ($_type == "priority" && empty($_SWIFT["prioritycache"][$_data]["priorityid"])) {
				$_errors[] = array("ticketid" => $_ticketObj->ticket["fticketid"], "type" => "propchange", "message" => sprintf($_SWIFT["language"]["invalidmobilepriority"], $_data));
				continue;
			}

			$_ticketObj->processTicketQueries();
		}
	}







	/**
	* ###############################################
	* TICKET DELETES
	* ###############################################
	*/
	if (_is_array($_tree["delete"]))
	{
		$_deletelist = $_deletekeylist = array();

		foreach ($_tree["delete"] as $key=>$val)
		{
			$_ticketid = $val["children"]["ticketid"][0]["values"][0];
			$_deletelist[] = $_ticketid;
			$_deletekeylist[$_ticketid] = 1;
		}

		$_successlist = $_failurelist = $_failurevallist = $_ticketpointer = array();

		$_failurelist = $_deletekeylist;

		if (_is_array($_deletelist) && $_SWIFT["staff"]["tdeleteticket"] != "0")
		{
			$_failurelist = array();
			$dbCore->query("SELECT `ticketid`, `ticketmaskid` FROM `". TABLE_PREFIX ."tickets` WHERE `ticketid` IN (". buildIN($_deletelist) .");");
			while ($dbCore->nextRecord())
			{
				$_ticketpointer[$dbCore->Record["ticketid"]] = $dbCore->Record["ticketmaskid"];
			}

			deleteTickets($_deletelist, true);

			$dbCore->query("SELECT `ticketid` FROM `". TABLE_PREFIX ."tickets` WHERE `ticketid` IN (". buildIN($_deletelist) .");");
			while ($dbCore->nextRecord())
			{
				$_failurelist[$dbCore->Record["ticketid"]] = 1;
			}
		}

		if (_is_array($_deletelist))
		{
			foreach ($_deletelist as $key=>$val)
			{
				if (!isset($_failurelist[$val]))
				{
					$_successlist[] = $val;
				} else {
					$_failurevallist[] = $val;
				}
			}
		}

		if (_is_array($_successlist))
		{
			foreach ($_successlist as $key=>$val)
			{
				$_success[] = array("ticketid" => $val, "ticketdisplayid" => iif($_SWIFT["settings"]["t_eticketid"]=="seq",$val, $_ticketpointer[$val]), "type" => "delete", "data" => "");
				$_successcount++;
			}
		}

		if (_is_array($_failurevallist))
		{
			foreach ($_failurevallist as $key=>$val)
			{
				if (empty($_ticketpointer[$val]))
				{
					$_errors[] = array("ticketid" => $val, "type" => "delete", "message" => sprintf($_SWIFT["language"]["kmnoticketexist"], $val));
				} else {
					$_errors[] = array("ticketid" => iif($_SWIFT["settings"]["t_eticketid"]=="seq",$val, $_ticketpointer[$val]), "type" => "delete", "message" => sprintf($_SWIFT["language"]["nopermdelkm"], iif($_SWIFT["settings"]["t_eticketid"]=="seq",$val, $_ticketpointer[$val])));
				}
			}
		}
	}









	// Dispatch the result
	$xml->addParentTag("mobile");

		$xml->addTag("successes", $_successcount);
		foreach ($_success as $key=>$val)
		{
			$xml->addParentTag("success");
				$xml->addTag("ticketid", intval($val["ticketid"]));
				$xml->addTag("ticketdisplayid", $val["ticketdisplayid"]);
				$xml->addTag("type", $val["type"]);
				$xml->addTag("data", $val["data"]);
			$xml->endTag("success");
		}

		$xml->addTag("errors", count($_errors));
		foreach ($_errors as $key=>$val)
		{
			$xml->addParentTag("error");
				$xml->addTag("ticketdisplayid", $val["ticketid"]);
				$xml->addTag("type", $val["type"]);
				$xml->addTag("message", $val["message"]);
			$xml->endTag("error");
		}

	$xml->endTag("mobile");

	$xml->echoXMLUTFWinapp();

} else {
	// Dispatch Invalid XML ERROR
	$xml->addParentTag("mobile");

		$xml->addTag("successes", "0");
		$xml->addTag("errors", "1");

		$xml->addParentTag("error");
			$xml->addTag("ticketdisplayid", "-");
			$xml->addTag("type", "general");
			$xml->addTag("message", $_SWIFT["language"]["invalidmobilexml"]);
		$xml->endTag("error");

	$xml->endTag("mobile");

	$xml->echoXMLUTFWinapp();
}
?>